package models

import (
	"context"
	"github.com/joho/godotenv"
	"github.com/redis/go-redis/v9"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"log"
	"os"
	"time"
)

var Mongo = InitMongo()
var RDB = InitRedis()

// 初始化MongoDB
func InitMongo() *mongo.Database {
	// 加载配置文件
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	//从.env文件中获取相关数据
	UserName_env := os.Getenv("MONGO_USERNAME")
	PassWord_env := os.Getenv("MONGO_PASSWORD")
	Mongo_Url_env := os.Getenv("MONGO_URL")
	Database_env := os.Getenv("MONGO_DATABASE")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	// 打印正在连接的信息
	log.Println("Connecting to MongoDB...")
	client, err := mongo.Connect(ctx, options.Client().SetAuth(options.Credential{
		Username: UserName_env,
		Password: PassWord_env,
	}).ApplyURI(Mongo_Url_env))
	if err != nil {
		log.Println(err)
		panic(err)

	}

	// 测试连接
	if err := client.Ping(ctx, readpref.Primary()); err != nil {
		log.Println("Failed to connect to MongoDB:", err)
		panic(err)
	} else {
		log.Println("MongoDB connection is healthy")
	}

	defer cancel() //确保函数在结束时释放资源
	return client.Database(Database_env)
}

func InitRedis() *redis.Client {
	client := redis.NewClient(&redis.Options{
		Addr:     os.Getenv("REDIS_URL"),
		Password: os.Getenv("REDIS_PASSWORD"),
		DB:       0,
	})
	// 进行错误捕获
	err := client.Ping(context.Background()).Err()
	if err != nil {
		log.Println("Failed to connect to Redis:", err.Error())
		panic(err)
	}
	return client
}
